#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "WangJing"
# Date: 2018/10/30

import time
from dingtalkchatbot.chatbot import DingtalkChatbot
from collections import Counter
import matplotlib.pyplot as plt
import math
import re

from weater_in import Spider
from weater_rule import Rule
from sql import Sql


def linefit(x, y):
    N = float(len(x))
    sx, sy, sxx, syy, sxy = 0, 0, 0, 0, 0
    for i in range(0, int(N)):
        sx += x[i]
        sy += y[i]
        sxx += x[i] * x[i]
        syy += y[i] * y[i]
        sxy += x[i] * y[i]
    a = (sy * sx / N - sxy) / (sx * sx / N - sxx)
    b = (sy - a * sx) / N
    if math.sqrt((sxx - sx * sx / N) * (syy - sy * sy / N)) == 0:
        r= 0
    else:
        r = abs(sy * sx / N - sxy) / math.sqrt((sxx - sx * sx / N) * (syy - sy * sy / N))
    return a, b, r


class Expression_travel(Rule):
    def __init__(self,set_weater,original_data,set_time,end_time,code_name_set,code_name_out,type=0,set_weater_back=None):
        super(Expression_travel,self).__init__(set_weater,original_data,set_time,end_time,code_name_set,code_name_out,type,set_weater_back)


    ############1.是否下雨###################
    def rain_travel(self):
        ###目的地天气规则
        ###是否下雨

        rain_data = self.rain()


        if rain_data:
            self.text += '{}起,{}未来{}天'.format(self.set_time, self.code_name_out, self.cut_time)
            self.text += '有雨，记得携带雨具\n'
        else:
            if self.type and self.fancheng():
                self.text +='{}{}返程有雨,记得携带雨具\n'.format(self.end_time,self.code_name_out)
            else:
                self.text += '{}起,{}未来{}天'.format(self.set_time, self.code_name_out, self.cut_time)
                weater = [x.split('转')[-1] for x in self.original_data['weater'].tolist()]
                print(Counter(weater))
                self.text +='{},不需携带雨具\n'.format(Counter(weater).most_common(1)[0][0])

    ############2.是否存在特殊天气################
    def spicial_travel(self):
        ##特殊天气
        specical_data = self.specical_weater()
        if specical_data:
            print(specical_data)
            for name,times in specical_data.items():
                print(name)
                self.text += '{}将有{}\n'.format(','.join(times),name)

    #######3.出发当天的天气比较####################
    def weater_start(self):
        #11月1日北京白天气温相比福州低5℃，夜间气温低12℃
        ###出发当天两地的温度对比
        max_weater_cut = int(self.original_data['wd_max'].tolist()[0]) - int(self.set_weater['wd_max'].tolist()[0])
        min_weater_cut = int(self.original_data['wd_min'].tolist()[0]) - int(self.set_weater['wd_min'].tolist()[0])
        weate_text = {}
        if abs(max_weater_cut)>2 or abs(min_weater_cut)>2:
            if max_weater_cut > 0:
                weate_text['max'] = '高'
            else:
                weate_text['max'] = '低'
            if min_weater_cut > 0:
                weate_text['min'] = '高'
            else:
                weate_text['min'] = '低'

            self.text += '{}{}白天气温相比{}{}{}℃，夜间气温{}{}℃ \n'.format(self.set_time,self.code_name_out, self.code_name_set,weate_text['max'],abs(max_weater_cut),
                                                              weate_text['min'],abs(min_weater_cut))
        else:
            self.text += '{}{}相比{}温度变化不大 \n'.format(self.set_time, self.code_name_out, self.code_name_set)

    ##########4.目的地温度变化#############
    def weater_process(self):
        # 目的地出发过程的天气
        # 未来15天温度持续降低，白天降至11℃，夜间降至1℃，请多带御寒衣物。
        ##未来趋势
        if int(self.cut_time) <= 3:
            wd_max = self.original_data['wd_max'].astype(int)
            wd_min = self.original_data['wd_min'].astype(int)
            self.text += '未来{}天，'.format(self.cut_time)
            if wd_max.max() == wd_max.min():
                self.text += '白天温度维持在{}℃,'.format(wd_max.min())
            else:
                self.text += '白天温度在{}~{}℃波动,'.format(wd_max.min(), wd_max.max())
            if wd_min.max() == wd_min.min():
                self.text += '夜间温度保持在{}℃'.format(wd_min.min())
            else:
                self.text += '夜间温度保持在{}~{}℃'.format(wd_min.min(), wd_min.max())

        else:
            x = range(len(self.original_data))
            a_max, b1, r1 = linefit(x, self.original_data['wd_max'].astype(int).tolist())
            a_min, b2, r2 = linefit(x, self.original_data['wd_min'].astype(int).tolist())

            wd_max = self.original_data['wd_max'].astype(int)
            wd_min = self.original_data['wd_min'].astype(int)
            ##白天上升趋势
            if  a_max >= 0.1:
                if a_min <= -0.1:
                    self.text += '未来{}天，白天温度持续上升，白天升至{}℃，昼夜温差较大，夜间最低温{}℃'.format(self.cut_time, wd_max.max(), wd_min.min())
                else:
                    self.text += '未来{}天，温度持续上升，白天升至{}℃，夜间升至{}℃'.format(self.cut_time, wd_max.max(), wd_min.max())
            ##白天下降趋势
            elif  a_max <= -0.1:

                if a_min >= 0.1:
                    self.text += '未来{}天，白天气温持续下降，白天降至{}℃，夜间回温，从{}℃升至{}℃'.format(self.cut_time, wd_max.min(), wd_min.min(),
                                                                                wd_min.max())
                else:
                    self.text += '未来{}天温度持续下降，白天降至{}℃，夜间降至{}℃，请多带御寒衣物。'.format(self.cut_time, wd_max.min(), wd_min.min())
            else:

                weater_comparison_data = self.weater_comparison()
                ##温度幅度是否很大
                original_low = weater_comparison_data[weater_comparison_data['original_low'] == 1]
                low_time = original_low['YBTM'].tolist()

                if len(low_time) >=1:
                    self.text += '未来{}天,{}起大幅降温,降至{}℃,夜间气温在{}~{}℃波动'.format(self.cut_time,low_time[0],wd_max.min(),wd_min.min(),wd_min.max())
                else:
                    if a_min <= -0.1:
                        self.text += '未来{}天,夜间气温持续下降,夜间降至{}℃,白天气温在{}~{}℃波动'.format(self.cut_time,wd_min.min(),wd_max.min(),wd_max.max())
                    elif a_min >= 0.1:
                        self.text += '未来{}天,夜间气温持续上升,从{}℃升至{}℃,白天气温在{}~{}℃波动'.format(self.cut_time, wd_min.min(),wd_min.max(),wd_max.min(), wd_max.max())
                    ##如果上面的都没有实现
                    else:
                        self.text += '未来{}天，温度变幅不大,白天平均温度{}℃，夜间平均温度{}℃'.format(self.cut_time,round(wd_max.mean()),round(wd_min.mean()))



    ############################################################
    def lucheng(self):
        type_dic = {0:'单程',1:'往返'}
        self.text += '{}--->{}({}~{})({})\n \n'.format(self.code_name_set,self.code_name_out,self.set_time,self.end_time ,type_dic[self.type] )



    def draw(self):
        a_max, b1, r1 = linefit(range(len(self.original_data)), self.original_data['wd_max'].astype(int).tolist())
        a_min, b2, r2 = linefit(range(len(self.original_data)), self.original_data['wd_min'].astype(int).tolist())
        test_y_max = [a_max * x + b1 for x in range(len(self.original_data))]
        test_y_min = [a_min * x + b2 for x in range(len(self.original_data))]
        plt.rcParams['font.sans-serif'] = ['SimHei']

        print('白天平均温度{},晚上平均温度{}'.format(self.original_data['wd_max'].astype(int).mean(),self.original_data['wd_min'].astype(int).mean()))
        x =self.original_data['YBTM'].tolist()# range(len(self.original_data))

        plt.plot(x, self.original_data['wd_max'].astype(int).tolist(), 'ro-', label="最大值")  # 蓝色--较好
        plt.plot(x, test_y_max, 'r',
                 label="max趋势")  # 红色
        plt.plot(x, self.original_data['wd_min'].astype(int).tolist(), 'bo-', label="最小值")  # 红色
        plt.plot(x, test_y_min, 'b',
                 label="min趋势")  # 红色
        plt.legend(loc="upper right")  # 显示图中的标签
        plt.xlabel("{}".format(self.code_name_out))
        plt.ylabel('温度')
        plt.xticks(rotation=45)
        plt.title('白天平均温度{},晚上平均温度{},\n最高温斜率:{},最低温斜率:{}'.format(round(self.original_data['wd_max'].astype(int).mean(),3),round(self.original_data['wd_min'].astype(int).mean()),round(a_max,3),round(a_min,3)))
        plt.show()


def ding(data):
    # WebHook地址
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=c023ebfff1eef6e24393f4f1d82c11a7a589edbcb10b56f4b7bbcf463091a67d'
    # 初始化机器人小丁
    xiaoding = DingtalkChatbot(webhook)
    # Text消息@所有人
    xiaoding.send_text(msg=data, is_at_all=None)


def Select_Sql(select_code):
 #根据用户的出行名称
    select_sql_set = 'select code from StnmCode where STNM= \'{}\''.format(select_code)
    sql_data = Sql()
    code_set = sql_data.Obtain_sql(select_sql_set)[0][0]

    return code_set


def main():
    code_name_set = '福州'
    code_name_out = '长沙'
    time_1 = '20181107'
    time_2 = '20181110'#  20181110     20181115    20181125
    now_time = time.strftime('%Y%m%d', time.localtime(time.time()))
    code_dic = {code_name_out:Select_Sql(code_name_out)}#,'上海':'101020100','海口':'101310101','昆明':'101290101','长沙':'101250101','海口'：'101310101','南宁':'101300101','三亚':'101310201'
    code_set = Select_Sql(code_name_set)#'101230101'  # 福州

    for name,code in code_dic.items():
        ###实时获取天气数据
        end_weater = Spider(code, time_1, time_2).spider_weater()
        set_weater = Spider(code_set, time_1, time_1).spider_weater()
        set_weater_back = Spider(code_set, time_2, time_2).spider_weater() ##返回日期的天气数据

        # 单程
        # print(set_weater)
        print(end_weater)
        #expression_travel_dc = Expression_travel(set_weater,end_weater,time_1,time_2,code_name_set,code_name_out)### 单程
        expression_travel_dc = Expression_travel(set_weater, end_weater, time_1, time_2, code_name_set, name,1, set_weater_back)##返程
        expression_travel_dc.lucheng()
        expression_travel_dc.rain_travel()
        expression_travel_dc.weater_start()
        expression_travel_dc.draw()

        expression_travel_dc.weater_process()

        print(expression_travel_dc.text)
        print('完成一次气象更新')

        if False:
            ding(expression_travel_dc.text)



if __name__ == '__main__':
    main()